package com.rxyb.security.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rxyb.core.respone.enums.CommonCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author YJH
 * @version 1.0
 * @description 没有访问得资源
 * @date 2020/5/25  16:14
 */
@Slf4j
public class BusiAccessDeniedHandler implements AccessDeniedHandler {


    public static final String MESSAGE = "没有访问得资源";


    /**
     * Handles an access denied failure.
     *
     * @param request               that resulted in an <code>AccessDeniedException</code>
     * @param response              so that the user agent can be advised of the failure
     * @param accessDeniedException that caused the invocation
     * @throws IOException      in the event of an IOException
     * @throws ServletException in the event of a ServletException
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        Map map = new HashMap(3);
        map.put("code", CommonCode.FAILED.getCode());
        map.put("msg", MESSAGE);
        map.put("data", null);
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(), map);
        } catch (Exception e) {
            log.error("返回资源权限不足出现异常", e);
        }
    }
}
